package org.bjf.modules.sys.web.controller;

import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.bjf.modules.core.web.core.PageVO;
import org.bjf.modules.core.web.core.ThreadContext;
import org.bjf.modules.sys.bean.SysMenu;
import org.bjf.modules.sys.bean.SysRole;
import org.bjf.modules.sys.bean.SysUser;
import org.bjf.modules.sys.query.SysUserQuery;
import org.bjf.modules.sys.service.SysMenuService;
import org.bjf.modules.sys.service.SysRoleService;
import org.bjf.modules.sys.service.SysUserService;
import org.bjf.utils.MD5Util;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

/**
 * 后台用户管理
 *
 * @author icemo
 */
@RestController
@RequestMapping("admin")
public class SysUserController {

  @Autowired
  private SysUserService sysUserService;
  @Autowired
  private SysUserService userService;
  @Autowired
  private SysRoleService roleService;
  @Autowired
  private SysMenuService menuService;

  @RequestMapping("sys-user/detail")
  public SysUser detail(@RequestParam long sysUserId) {
    return sysUserService.get(sysUserId);
  }

  @RequestMapping("sys-user/list")
  public List<SysUser> list(SysUserQuery query) {
    return sysUserService.list(query);
  }

  @RequestMapping("sys-user/listPage")
  public PageVO<SysUser> listPage(SysUserQuery query) {
    return sysUserService.listPage(query);
  }

  @RequestMapping("sys-user/listAll")
  public List<SysUser> listAll(SysUserQuery query) {
    return sysUserService.listAll(query);
  }


  @RequestMapping("sys-user/add")
  public void add(@Validated SysUser user) {
    user.setPassword(MD5Util.encode("123456"));
    sysUserService.add(user);
  }

  @RequestMapping("sys-user/update")
  public void update(@Validated SysUser user) {
    if (StringUtils.isNotBlank(user.getPassword())) {
      user.setPassword(MD5Util.encode(user.getPassword()));
    }
    sysUserService.updateById(user);
  }

  @RequestMapping("sys-user/delete")
  public void delete(@RequestParam long sysUserId) {
    sysUserService.deleteById(sysUserId);
  }

  /**
   * 查询用户的所有角色
   */
  @RequestMapping("sys-user/list-role")
  public List<SysRole> listRole() {
    long sysUserId = ThreadContext.getLoginInfo().getUserId();
    return roleService.listByUser(sysUserId);
  }

  /**
   * 更新用户角色（分配角色）
   */
  @RequestMapping("sys-user/update-role")
  public void updateRole(@RequestParam Long sysUserId, @RequestParam String roleIds) {
    userService.updateRole(sysUserId, roleIds);
  }

  /**
   * 查询用户的所有菜单
   */
  @RequestMapping("sys-user/list-menu")
  public List<SysMenu> listMenu() {
    long sysUserId = ThreadContext.getLoginInfo().getUserId();
    return menuService.listByUser(sysUserId);
  }
}
